const fs = require('fs');
const path = require('path');

// 生成路由数组方法
function generateRoutes(dir, basePath) {
    const files = fs.readdirSync(dir);
    return files.flatMap((file)=>{
        const fullPath = path.resolve(dir, file);
        const relativePath = path.relative(basePath, fullPath);
        if(fs.statSync(fullPath).isDirectory()){
            return generateRoutes(fullPath, basePath);
        }
        if(file.endsWith(".vue")){
            const routePath = relativePath
            .replace(/\\/g, "/")
            .replace(/\.vue$/, "")
            .replace(/\/index$/, "")
            .replace(/\/_/g, "/:");
            const parts = routePath.split("/").filter(Boolean);

            if (
                parts.length > 1 &&
                parts[parts.length - 1] === parts[parts.length - 2]
            ){
                parts.pop();
            }

            const finalPath = "/" + parts.join("/").toLowerCase();

            const metaFilePath = fullPath.replace(".vue", ".meta.js");
            const meta = fs.existsSync(metaFilePath) ? require(metaFilePath) : {};

            return [
                {
                path: finalPath,
                component: fullPath,
                ...meta,
                },
            ];
        }

        return [];
    })
}

module.exports = function VitePluginAutoRoutes(options = {}) {
  const { pagesDir = "src/views", routesFile = "src/router/autoRoutes.js" } =
    options;
  return {
    name: "vite-plugin-auto-routes",
    configResolved(config) {
      const pagesPath = path.resolve(config.root, pagesDir);
      // 生成路由数组
      const routes = generateRoutes(pagesPath, pagesPath);

      const routesFileContent = `
        export const routes = ${JSON.stringify(routes, null, 2)};
      `;

      fs.writeFileSync(
        path.resolve(config.root, routesFile),
        routesFileContent
      );
    },
  };
};